using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;

namespace StorytellingScript
{
    [GlobalMethods]
    public static class Global
    {
        public static void AplicarPadrao()
        {
            jQueryObject body = jQuery.Select("body");
            body.CSS("display", "none");
            body.FadeIn(1000);

            jQuery.Select(".Transicao").Click(new jQueryEventHandler(delegate(jQueryEvent e)
            {
                body.FadeOut(1000);
            }));

            jQuery.Select(".DataTable").Plugin<StorytellingPlugin>().DataTable(new Dictionary(
                    "bPaginate", true,
                    "bFilter", false,
                    "sPaginationType", "full_numbers",
                    "sDom", "RC<\"clear\">lfrtip",
                    "aoColumnDefs", new object[] { new Dictionary(
                        "aTargets", new object[] { 1 }                        
                        )},
                    "oColVis", new Dictionary(
                        "buttonText", "Exibir/Ocultar colunas"
                        ),
                    "oLanguage", new Dictionary(
                        "sLengthMenu", "Mostrar _MENU_ registros por p&aacutegina",
                        "sZeroRecords", "Nada foi encontrado",
                        "sInfo", "Mostrando _START_ &agrave _END_ de _TOTAL_ registros",
                        "sInfoEmpty", "Mostrando 0 &agrave 0 de 0 registros",
                        "sInfoFiltered", "(Filtrado por _MAX_ total de registros)",
                        "oPaginate", new Dictionary(
                            "sFirst", "Primeiro",
                            "sLast", "&Uacuteltimo",
                            "sPrevious", "Anterior",
                            "sNext", "Pr&oacuteximo"
                            )
                    )));

            jQuery.Select(".Tabs").Plugin<StorytellingPlugin>().Tabs();

            jQuery.Select(".Dialog").Plugin<StorytellingPlugin>().Dialog(new Dictionary(
                "autoOpen", false,
                "closeText", "",
                "resizable", false,
                "Height", "400",
                "Width", "800",
                "minHeight", "400",
                "minWidth", "800",
                "maxHeight", "400",
                "maxWidth", "800"
                ));

            Dictionary dictionary = new Dictionary("placeholder", " ");
            Dictionary dictionaryAtributo = new Dictionary("placeholder", "1");
            Dictionary dictionaryHabilidade = new Dictionary("placeholder", "0");

            jQuery.Select(".InteiroUmaCasa").Plugin<StorytellingPlugin>().Mask("9", dictionary);
            jQuery.Select(".InteiroDuasCasa").Plugin<StorytellingPlugin>().Mask("9?9", dictionary);
            jQuery.Select(".InteiroTresCasa").Plugin<StorytellingPlugin>().Mask("9?99", dictionary);

            jQuery.Select(".InteiroAtributo").Each(new ElementIterationCallback(delegate(int index, Element element)
                {
                    jQueryObject campo = jQuery.FromElement(element);
                    campo.Plugin<StorytellingPlugin>().Mask("9", dictionaryAtributo);
                    if (campo.GetValue() == "")
                    {
                        campo.Value("1");
                    }
                }));

            jQuery.Select(".InteiroHabilidade").Each(new ElementIterationCallback(delegate(int index, Element element)
                {
                    jQueryObject campo = jQuery.FromElement(element);
                    campo.Plugin<StorytellingPlugin>().Mask("9", dictionaryHabilidade);
                    if (campo.GetValue() == "")
                    {
                        campo.Value("0");
                    }
                }));
        }

        public static void Autocompletar(string controlador)
        {
            jQuery.Select(string.Format(".Autocompletar{0}", controlador)).Each(new ElementIterationCallback(delegate(int index, Element element)
                {
                    string formElementName = jQuery.FromElement(element).GetAttribute("name");
                    string hiddenElementID = string.Format("{0}Autocomplete_{1}", formElementName, index);
                    jQuery.FromElement(element).Plugin<StorytellingPlugin>().Autocomplete(new Dictionary(
                        "source", new Action<object, Action<object>>(delegate(object request, Action<object> response) 
                            {
                                jQueryAjaxOptions options = new jQueryAjaxOptions();
                                options.Url = string.Format("/{0}/Autocompletar", controlador);
                                options.Type = "POST";
                                options.DataType = "json";
                                options.Data = new Dictionary("nome", Script.Literal("{0}.term", request));
                                options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                                    {
                                        response(jQuery.Map(data, new ObjectMapCallback(delegate(object item, string key)
                                            {
                                                return new Dictionary("label", Script.Literal("{0}.Nome", item), "value", Script.Literal("{0}.Id", item));
                                            })));
                                    });

                                jQuery.Ajax(options);
                            }),
                        "focus", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui) 
                            {
                                jQuery.FromElement(element).Value(Script.Literal("{0}.item.label", ui).ToString());
                                return false;
                            }),
                        "select", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui) 
                            {
                                jQuery.FromElement(element).Value(Script.Literal("{0}.item.label", ui).ToString());
                                jQueryObject inputHidden = jQuery.Select(string.Format("#{0}", hiddenElementID));

                                if (inputHidden.Length == 0)
                                {
                                    jQuery.FromElement(element).After(string.Format(Template.Autocompletar, formElementName, hiddenElementID, 
                                        Script.Literal("{0}.item.value", ui)));
                                }
                                else
                                {
                                    inputHidden.Value(Script.Literal("{0}.item.value", ui).ToString());
                                }
                                return false;
                            })
                        ));
                }));
        }

        public static void LimparAutocompletar(string autocompletar)
        {
            jQuery.Select(string.Format("#{0}", autocompletar)).Value("");
            jQueryObject valor = jQuery.Select(string.Format("#{0}Autocomplete_0", autocompletar));
            if (valor.Length != 0)
            {
                valor.Value("0");
            }
        }

        public static string Pontos(int quant)
        {
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < quant; i++)
            {
                stringBuilder.Append("\u25CF");
            }

            return stringBuilder.ToString();
        }

        public static void ConfigurarVantagemNivel()
        {
            jQuery.Select(".AutocompletarVantagem").Each(new ElementIterationCallback(delegate(int index, Element element)
                {
                    jQueryObject vantagem = jQuery.FromElement(element);
                    jQueryObject vantagemNivel = vantagem.Parent().Parent().Find(":input[name=HumanoVantagemVantagemNivel]");               
                    vantagem.Plugin<StorytellingPlugin>().Bind("autocompleteselect",
                        new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui) 
                        {
                            jQueryAjaxOptions options = new jQueryAjaxOptions();
                            options.Url = "/Vantagem/CarregarVantagemNiveis";
                            options.Type = "POST";
                            options.DataType = "json";
                            options.Data = new Dictionary("id", Script.Literal("{0}.item.value", ui));
                            options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                            {
                                vantagemNivel.Html("");
                                jQuery.Each(data, new ObjectIterationCallback(delegate(string name, object value)
                                {
                                    vantagemNivel.Append(string.Format(Template.Combo, value, Pontos(Int32.Parse(value.ToString()))));
                                }));
                            });

                            jQuery.Ajax(options);
                            return false;
                        }));
                    vantagemNivel.Bind("focus", new jQueryEventHandler(delegate(jQueryEvent e)
                        {
                            jQueryAjaxOptions options = new jQueryAjaxOptions();
                            options.Url = "/Vantagem/CarregarVantagemNiveis";
                            options.Type = "POST";
                            options.DataType = "json";
                            options.Data = new Dictionary("id", vantagemNivel.Parent().Parent()
                                .Find(":input[name=HumanoVantagemVantagemValor]").GetValue());
                            options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                            {
                                string valor = vantagemNivel.GetValue();
                                vantagemNivel.Html("");
                                jQuery.Each(data, new ObjectIterationCallback(delegate(string name, object value)
                                {   
                                    vantagemNivel.Append(string.Format(Template.Combo, value, Pontos(Int32.Parse(value.ToString()))));
                                }));
                                vantagemNivel.Value(valor);
                            });

                            jQuery.Ajax(options);
                        }));
                }));
        }

        public static void Clonar(string idDiv)
        {
            jQueryObject contador = jQuery.Select(string.Format("#contador_{0}", idDiv));
            jQueryObject div = jQuery.Select(string.Format("#{0}", idDiv)).Clone().Attribute("id", string.Format("{0}_{1}", idDiv, contador.GetValue()));
            div.Html(string.Format(Template.Clone, idDiv, contador.GetValue(), div.GetHtml()));
            div.InsertBefore(string.Format("#cloneHidden_{0}", idDiv));
            contador.Value((Int32.Parse(contador.GetValue()) + 1).ToString());
            AplicarPadrao();
            Importados.AplicarPosClone();
        }

        public static void ExcluirRemoverClone(string idDiv, int index, string entidade, long idEntidade)
        {
            jQuery.Select(string.Format(Template.Lixeira, entidade, idEntidade))
                .InsertBefore(string.Format("#contador_{0}", idDiv));
            RemoverClone(idDiv, index);
        }

        public static void RemoverClone(string idDiv, int index)
        {
            jQueryObject contador = jQuery.Select(string.Format("#contador_{0}", idDiv));
            jQuery.Select(string.Format("#{0}_{1}", idDiv, index)).Remove();
            contador.Value((Int32.Parse(contador.GetValue()) - 1).ToString());
        }

        public static void Exibir(Element element, string comp, string rotuloEsconder, string rotuloAparecer)
        {
            if (element.InnerHTML == rotuloEsconder)
            {
                element.InnerHTML = rotuloAparecer;
            }
            else
            {
                element.InnerHTML = rotuloEsconder;
            }

            jQuery.Select(string.Format("#{0}", comp)).Plugin<StorytellingPlugin>().Toggle("slow");
        }

        public static void ExcluirItemGrid(string url)
        {
            if (Script.Confirm("Deseja excluir esse item?"))
            {
                Redirecionar(url);
            }
        }

        public static void Redirecionar(string url)
        {
            jQueryObject body = jQuery.Select("body");

            body.FadeOut(1000, new Action(delegate()
            {
                Window.Location.Href = url;
            }));
        }

        public static void Visualizar(string url)
        {
            Window.Location.Href = url;
        }

        public static void RolarTopo()
        {
            jQuery.Select("html, body").Animate(new Dictionary("scrollTop", "0px"));
        }        
        
        public static void RolarFundo()
        {
            jQuery.Select("html, body").Animate(new Dictionary("scrollTop", jQuery.Document.GetHeight()));
        }

        public static void AplicarFacebook()
        {
            string script = "script";
            string id = "facebook-jssdk";
            Element fjs = Window.Document.GetElementsByTagName(script)[0];
            if (Script.Boolean(Window.Document.GetElementById(id))) return;
            ScriptElement js = (ScriptElement)Window.Document.CreateElement(script);
            js.ID = id;
            js.Src = "//connect.facebook.net/pt_BR/all.js#xfbml=1";
            fjs.ParentNode.InsertBefore(js, fjs);
        }

        public static void AplicarGoogle()
        {
            string script = "script";
            Script.Literal("{0}.___gcfg={1}", Window.Self, new Dictionary("lang", "pt-BR"));
            ScriptElement po = (ScriptElement)Window.Document.CreateElement(script);
            po.Type = "text/javascript";
            Script.Literal("{0}.async=true", po);
            po.Src = "https://apis.google.com/js/plusone.js";
            Element s = Window.Document.GetElementsByTagName(script)[0];
            s.ParentNode.InsertBefore(po, s);
        }
    }
}
